﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using TweetStream.Extensions.Contracts;
using System.Text.RegularExpressions;
using System.Net;
using System.Windows.Media.Imaging;
using System.IO;

namespace TweetStream.Extensions.YouTube
{
    [Export(typeof(IThirdPartyContent))]
	public partial class InlineHtml : UserControl, IThirdPartyContent
	{

        //public delegate void ShowImageUriHandler(object sender, IHLArgs args);
        //public delegate void ShowHtmlUriHandler(object sender, IHTMLArgs args);

        //public event ShowImageUriHandler ShowImageUri;
        //public event ShowHtmlUriHandler ShowHtmlUri;

        private const int  const_timeSecondsToWaitForBrush = 5;

		public InlineHtml()
		{
			// Required to initialize variables
			InitializeComponent();
		}


        #region Source


        public Uri Source
        {
            get { return (Uri)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(Uri), typeof(InlineHtml), new PropertyMetadata(SourceChanged));

        private static void SourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            ((InlineHtml)obj).wbMain.Source = (Uri)args.NewValue;
        }
        #endregion


        void IThirdPartyContent.InitControl(InitMessage msg)
        {
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            //wc.OpenReadAsync(this.LinkUri);

            State st = new State()
            {
                DynamicControlsContainer = msg.DynamicControlsContainer,
                Url = msg.Url,
                Key = msg.Key,
                Uri = new Uri(msg.Url, UriKind.Absolute),
                LoadingAnimation = msg.LoadingAnimation,
                LoadingAnimationContainer = msg.LoadingAnimationContainer

            };
            wc.DownloadStringAsync(new Uri(msg.Url), st);
        }


        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            State st = (State)e.UserState;

            try
            {
                string res = e.Result;



                UserControl ctl = DoCheck(st.Key, res);

                if (ctl != null)
                {
                    string sType = ctl.GetType().Name;

                    if (sType.ToLower().Contains("image"))
                    {
                        ctl.UpdateLayout();
                        st.DynamicControlsContainer.Children.Clear();
                        st.DynamicControlsContainer.Children.Add(ctl);
                        st.DynamicControlsContainer.Visibility = Visibility.Visible;
                        st.DynamicControlsContainer.Height += (ctl).ActualHeight;
                        
                        //if (ShowImageUri != null) ShowImageUri(ctl, new IHLArgs(st.DynamicControlsContainer));
                    }
                    else if (sType.ToLower().Contains("html"))
                    {
                        ctl.UpdateLayout();
                        st.DynamicControlsContainer.Children.Clear();
                        st.DynamicControlsContainer.Children.Add(ctl);
                        st.DynamicControlsContainer.Visibility = Visibility.Visible;
                        st.DynamicControlsContainer.Height += (ctl).ActualHeight;
                        
                        //if (ShowHtmlUri != null) ShowHtmlUri(ctl, new IHTMLArgs(st.DynamicControlsContainer));
                    }


                }


            }
            catch { }
            finally
            {
                st.LoadingAnimation.Stop();
                st.LoadingAnimationContainer.Children.Clear();
            }

        }

        UserControl IThirdPartyContent.DoCheck(string key, string contentToParse)
        {
            return DoCheck(key, contentToParse);
        }

        UserControl DoCheck(string key, string contentToParse)
        {
            if (key == "youtube")
            {
                
                Match match = System.Text.RegularExpressions.Regex.Match(contentToParse, "(?<=\\?v=)([-a-zA-Z0-9_-]+)");
                if (match.Success)
                {
                    InlineHtml ctl = new InlineHtml()
                    {
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        VerticalAlignment = System.Windows.VerticalAlignment.Top,
                        Source = new Uri("http://677139bbe83643508c9775683f63d5b0.cloudapp.net/Hook_YouTube.aspx?url=" + match.Groups[1].Value + "&w=220&h=180", UriKind.RelativeOrAbsolute),
                        Width = 260,
                        Height = 220
                    };
                    return ctl;
                }
            }

            return null;
        }


        bool IThirdPartyContent.CheckIfAutoLoad(string key)
        {
            if (key == "youtube") return true;

            return false;
        }

        public string RetrieveKey(string url)
        {
            if (url.ToLower().Contains("youtube.com")) return "youtube";
            else return string.Empty;
        }

        System.Windows.Threading.DispatcherTimer dt;
        private void wbMain_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            //get image of it
            //SnapPicture(wbMain);
            //remove htmlbrowsercontrol
            //htmlBrush.Redraw();
            //wbMain.Visibility = Visibility.Collapsed;
            //brush.Visibility = Visibility.Visible;
            if (dt == null)
            {
                dt = new System.Windows.Threading.DispatcherTimer();
                dt.Interval = TimeSpan.FromSeconds(const_timeSecondsToWaitForBrush);
                dt.Tick += new EventHandler(dt_Tick);
            }
            dt.Start();

        }

        void dt_Tick(object sender, EventArgs e)
        {
            dt.Stop();
            htmlBrush.Redraw();
            wbMain.Visibility = Visibility.Collapsed;
            brush.Visibility = Visibility.Visible;
        }

        private void SnapPicture(FrameworkElement elm)
        {
            WriteableBitmap bitmap = new WriteableBitmap(elm, new TranslateTransform());

            EditableImage imageData = new EditableImage(bitmap.PixelWidth, bitmap.PixelHeight);


            for (int y = 0; y < bitmap.PixelHeight; ++y)
            {

                for (int x = 0; x < bitmap.PixelWidth; ++x)
                {

                    int pixel = bitmap.Pixels[bitmap.PixelWidth * y + x];

                    imageData.SetPixel(x, y,
                                (byte)((pixel >> 16) & 0xFF),
                                (byte)((pixel >> 8) & 0xFF),
                                (byte)(pixel & 0xFF),
                                (byte)((pixel >> 24) & 0xFF)
                                );

                }

            }

            Stream pngStream = imageData.GetStream();

            //imgMain.Source = bitmap;
            //imgMain.Width = 350;
            //imgMain.Visibility = Visibility.Visible;
            //wbMain.Visibility = Visibility.Collapsed;
            //Interaction.GetBehaviors(img).Add(new MouseDragElementBehavior());


            //grdPlayArea.Children.Add(ps);

        }
    }


    public class State
    {
        public Grid DynamicControlsContainer { get; set; }
        public string Key { get; set; }
        public string Url { get; set; }
        public Uri Uri { get; set; }
        public Storyboard LoadingAnimation { get; set; }
        public Grid LoadingAnimationContainer { get; set; }
    }

}